<template>
  <div class="pagination" @chick="changePageNo">
    <button :disabled="startAndEnd.startPage===1" :data-page="pageNo-1">上一页</button>
    <button v-show="startAndEnd.startPage>1" :data-page="1">1</button>
    <span v-show="startAndEnd.startPage>2">···</span>

    <!-- 可以多种方案实现 -->
    <button :class="{active:pageNo===(startAndEnd.startPage+index)}" :data-page="startAndEnd.startPage+item-1"
      v-for="(item,index) in (startAndEnd.endPage-startAndEnd.startPage+1)" :key="index">
      {{startAndEnd.startPage+item-1}}
    </button>

    <span v-show="startAndEnd.endPage<pageSum-1">···</span>
    <button v-show="startAndEnd.endPage<pageSum" :data-page="pageSum">{{pageSum}}</button>
    <button :disabled="startAndEnd.endPage===pageSum" :data-page="pageNo+1">下一页</button>

    <span>共 {{total}} 条</span>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  methods: {
    changePageNo (e) {
      this.$emit('change-page-no', e.target.dataset.page)
    }
  },
  computed: {
    pageSum () {
      return Math.ceil(this.total / this.pageSize)
    },
    startAndEnd () {
      let startPage = 1
      let endPage = 1
      if (this.continue > this.pageSum) {
        endPage = this.pageSum
      } else {
        startPage = this.pageNo - (this.continue - 1) / 2;
        endPage = this.pageNo + (this.continue - 1) / 2;
        if (startPage < 1) {
          startPage = 1
          endPage = this.continue
        }
        if (endPage > this.pageSum) {
          endPage = this.pageSum
          startPage = endPage - this.continue + 1
        }
      }
      return {
        startPage,
        endPage
      }
    }
  },
  props: {
    total: Number,
    continue: {
      type: Number,
      default: 5
    },
    //当前页码
    pageNo: {
      type: Number,
      required: true,
    },
    //一页有几个
    pageSize: {
      type: Number,
      default: 10
    }
  },
}

</script>

<style lang="less" scoped>
.pagination {
  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: gray;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }

  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>